package com.shambles.manage2.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shambles.manage2.dto.CountNumDTO;
import com.shambles.manage2.dto.CountRateDTO;
import com.shambles.manage2.service.CattleService;
import com.shambles.manage2.service.CostService;
import com.shambles.manage2.tkmapper.entity.*;
import com.shambles.manage2.tkmapper.mapper.*;
import com.shambles.manage2.utils.CommonUtils;
import com.shambles.manage2.utils.ObjectUtils;
import com.shambles.manage2.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangsy
 * @description
 * @date 2020/03/01
 */
@Service
public class CostServiceImpl implements CostService {

    @Autowired
    private CostMapper costMapper;
    @Autowired
    private CostDetailMapper costDetailMapper;
    @Autowired
    private AdmissionRegisterMapper admissionRegisterMapper;
    @Autowired
    private CattleService cattleService;
    @Autowired
    private SysLogMapper sysLogMapper;
    @Autowired
    private SubscribeInformationMapper subscribeInformationMapper;
    @Autowired
    private AbattoirBoothMapper abattoirBoothMapper;

    /**
     * 费用填写接口
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertCost(Cost insertCost, List<CostDetail> detailList) {
//        Cost insertCost=new Cost();
        int totalNumber = 0;
        float money = 0;
        int tquaNumber = 0;
//        BeanUtils.copyProperties(cost,insertCost);
        insertCost.setGuid(IdUtil.simpleUUID());
        insertCost.setPersonnelGuid(CommonUtils.getCurrentUserGuid());
        insertCost.setPersonnelName(CommonUtils.getCurrentUserName());
        //获取系统的当前时间
        insertCost.setTime(System.currentTimeMillis());
        //将摊位明细反写到费用明细表中(入场GUID)
        String admissionguid = insertCost.getAdmissionGuid();
        //查询摊位明细
//        List<AbattoirBoothDetail> abattoirBoothDetail =this.abattoirBoothMapper.queryBoothDetailByGuid(admissionguid);
        Map<String, Cattle> cattleMap = cattleService.getCattleMap();
        for (CostDetail costDetail : detailList) {
            costDetail.setGuid(IdUtil.simpleUUID());
            costDetail.setTotalGuid(insertCost.getGuid());
            //求和数量
            totalNumber += costDetail.getNumber();
            //求和金额
            costDetail.setPrice(cattleMap.get(costDetail.getCattleGuid()).getPrice());
            costDetail.setMoney(costDetail.getNumber() * costDetail.getPrice());
            money += costDetail.getMoney();
            tquaNumber += costDetail.getQuarantineNumber();
        }

        insertCost.setMoney(money);
        insertCost.setNumber(totalNumber);
        insertCost.setQuarantineNumber(tquaNumber);
        admissionRegisterMapper.updateState(1, insertCost.getAdmissionGuid());
        this.costMapper.insertSelective(insertCost);
        this.costDetailMapper.insertList(detailList);

        if (abattoirBoothMapper.queryUser(insertCost.getBoothGuid()).isEmpty()) {
            abattoirBoothMapper.updateState(0, insertCost.getBoothGuid());
        }
        //添加系统日志
        SysLog sysLog = new SysLog();
        sysLog.setGuid(IdUtil.simpleUUID());
        sysLog.setOperationPeople(CommonUtils.getCurrentUserName());
        sysLog.setFunctionName("出场");
        sysLog.setContent(CommonUtils.getCurrentUserName() + "操作出场功能");
        sysLog.setOperationTime(System.currentTimeMillis());
        this.sysLogMapper.insertSelective(sysLog);
    }

    /**
     * 费用查询
     */
    public PageInfo<Cost> querCostAll(MessageRequestVM messageRequestVM) {
        return PageHelper.startPage(messageRequestVM.getPageIndex(), messageRequestVM.getPageSize()).doSelectPageInfo(() ->
                costMapper.querCostAll()
        );
    }

    @Override
    public void confirm(Cost cost) {
        Weekend<Cost> costWeekend = new Weekend<>(Cost.class);
        costWeekend.weekendCriteria().andEqualTo(Cost::getGuid, cost.getGuid());
        cost.setGuid(null);
        costMapper.updateByExampleSelective(cost, costWeekend);
    }

    @Override
    public Map<String, List<Map<String, Object>>> count(Long startTime, Long endTime) {
        if (startTime == null) {
            startTime = TimeUtils.getMoth0();
        }
        if (endTime == null) {
            endTime = System.currentTimeMillis();
        }
        List<Map<String, Object>> costCount = costMapper.count(startTime, endTime);
        List<Map<String, Object>> subCount = subscribeInformationMapper.count(startTime, endTime);
        //已宰杀数量统计
        List<Map<String, Object>> numberCount = new ArrayList<>();
        //已检疫数量统计
        List<Map<String, Object>> quarantineCount = new ArrayList<>();
        //宰杀的金额统计
        List<Map<String, Object>> moneyCount = new ArrayList<>();
        for (Map<String, Object> map : costCount) {
            Map<String, Object> numberCountMap = new HashMap<>();
            numberCount.add(numberCountMap);
            numberCountMap.put("name", map.get("name"));
            numberCountMap.put("value", map.get("number"));

            Map<String, Object> quarantineCountMap = new HashMap<>();
            quarantineCount.add(quarantineCountMap);
            quarantineCountMap.put("name", map.get("name"));
            quarantineCountMap.put("value", map.get("quarantine"));

            Map<String, Object> moneyCountMap = new HashMap<>();
            moneyCount.add(moneyCountMap);
            moneyCountMap.put("name", map.get("name"));
            moneyCountMap.put("value", map.get("money"));
        }
        HashMap<String, List<Map<String, Object>>> resultMap = new HashMap<>();
        resultMap.put("sub", subCount);
        resultMap.put("numberCount", numberCount);
        resultMap.put("quarantineCount", quarantineCount);
        resultMap.put("moneyCount", moneyCount);
        return resultMap;
    }

    @Override
    public CountNumDTO countNum(String filed, Long sTime, Long eTime) {
        if (ObjectUtils.isEmpty(sTime)) {
            sTime = TimeUtils.getMoth0();
        }
        if (ObjectUtils.isEmpty(eTime)) {
            eTime = System.currentTimeMillis();
        }
        List<String> dayList = TimeUtils.getDayList(sTime, eTime);
        CountNumDTO countNumDTO = new CountNumDTO();
        countNumDTO.setDate(dayList);
        List<String> titleData = countNumDTO.getTitleData();
        for (Map.Entry<String, Cattle> cattleEntry : cattleService.getCattleMap().entrySet()) {
            titleData.add(cattleEntry.getValue().getType());
            List<Map<String, Object>> detail = costDetailMapper.countNumByCattleGuid(filed, cattleEntry.getKey(), sTime, eTime);
            HashMap<String, Object> map = new HashMap<>();
            for (Map<String, Object> detailMap : detail) {
                map.put(detailMap.get("nTime").toString(), detailMap.get("number").toString());
            }
            List<Object> dataList = new ArrayList<>();
            for (String s : dayList) {
                if (map.get(s) == null) {
                    dataList.add(0);
                } else {
                    dataList.add(map.get(s));
                }
            }
            countNumDTO.getData().add(dataList);
        }
        return countNumDTO;
    }

    @Override
    public List<Map<String, Object>> countByUser(Long sTime, Long eTime) {
        if (ObjectUtils.isEmpty(sTime)) {
            sTime = TimeUtils.getMoth0();
        }
        if (ObjectUtils.isEmpty(eTime)) {
            eTime = System.currentTimeMillis();
        }
        return costDetailMapper.countByUser(sTime, eTime);
    }

    @Override
    public List<Map<String, Object>> countByUserDetail(String userGuid, Long sTime, Long eTime) {
        if (ObjectUtils.isEmpty(sTime)) {
            sTime = TimeUtils.getMoth0();
        }
        if (ObjectUtils.isEmpty(eTime)) {
            eTime = System.currentTimeMillis();
        }
        return costDetailMapper.countByUserDetail(userGuid, sTime, eTime);
    }

    @Override
    public List<Map<String, Object>> countByUsersDetail(Long sTime, Long eTime) {
        if (ObjectUtils.isEmpty(sTime)) {
            sTime = TimeUtils.getMoth0();
        }
        if (ObjectUtils.isEmpty(eTime)) {
            eTime = System.currentTimeMillis();
        }
        return costDetailMapper.countByUsersDetail(sTime, eTime);
    }

    @Override
    public CountRateDTO countRateByType(Long sTime, Long eTime) {
        if (ObjectUtils.isEmpty(sTime)) {
            sTime = TimeUtils.getMoth0();
        }
        if (ObjectUtils.isEmpty(eTime)) {
            eTime = System.currentTimeMillis();
        }
        CountRateDTO countRateDTO = new CountRateDTO(sTime, eTime);
        List<String> titleData = countRateDTO.getTitleData();
        for (Map.Entry<String, Cattle> cattleEntry : cattleService.getCattleMap().entrySet()) {
            titleData.add(cattleEntry.getValue().getType());
            List<Map<String, Object>> reteList = costDetailMapper.countRateByCattleGuid(cattleEntry.getKey(), sTime, eTime);
            HashMap<String, Map<String, Object>> map = new HashMap<>();
            for (Map<String, Object> detailMap : reteList) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("number", detailMap.get("number"));
                map1.put("value", detailMap.get("rate"));
                map.put(detailMap.get("nTime").toString(), map1);
            }
            List<Map<String, Object>> dataList = new ArrayList<>();
            HashMap<String, Object> emptyMap = new HashMap<>();
            emptyMap.put("number", 0);
            emptyMap.put("value", 0);
            for (String s : countRateDTO.getDate()) {
                if (map.get(s) == null) {
                    dataList.add(emptyMap);
                } else {
                    dataList.add(map.get(s));
                }
            }
            countRateDTO.getData().add(dataList);
        }
        return countRateDTO;
    }
}
